#light
open System
open Schema

open Lucene.Net

(* Document types *)
type DocField = string * string
type Document = { Schema : IndexSchema; Fields : DocField list }

let sampleDoc = { 
    Schema = defaultSchema;
    Fields = 
        [
            ("ID", "ASDF");
            ("PublishDate", DateTime.Now.ToString());
            ("Title", "This is a title");
            ("Excerpt", "My title was non-obvious");
            ("Body", "Lorem ipsum ad infinum");
        ] }

(*let buildField2 (schema : IndexSchema) (field : DocField) = 
    let getOptions l init = 
        let name, value, store, index = init
        match l with
        | h :: t ->
            match h with
            | FieldOption.Stored -> 
                (name, value, Documents.Field.Store.YES, index)
            | FieldOption.Compressed -> 
                (name, value, Documents.Field.Store.COMPRESS, index)
            | FieldOption.Indexed -> 
                (name, value, store, Documents.Field.Index.UN_TOKENIZED)
            | FieldOption.Tokenized -> 
                (name, value, store, Documents.Field.Index.TOKENIZED)
            | FieldOption.Type(t) -> 
                (name, format t value, store, index)
            // The following aren't relevant here
            | FieldOption.Required | FieldOption.Unique
            | FieldOption.MultiValue -> init
        | [] -> init
            
    let name, value, store, index = 
        (
            fst field, 
            snd field, 
            Documents.Field.Store.NO, 
            Documents.Field.Index.TOKENIZED
        )
            |> getOptions (getSchemaField schema (fst field))
                        
    let lfield = new Documents.Field(name, value, store, index)
    lfield*)

let buildField (schema : IndexSchema) (field : DocField) = 
    let name = ref (fst field)
    let value = ref (snd field)
    let store = ref Documents.Field.Store.NO
    let index = ref Documents.Field.Index.TOKENIZED
    
    let options = getSchemaField schema !name
       
    let setOption o =
        match o with
        | FieldOption.Stored -> store := Documents.Field.Store.YES
        | FieldOption.Compressed -> store := Documents.Field.Store.COMPRESS
        | FieldOption.Indexed -> index := Documents.Field.Index.UN_TOKENIZED
        | FieldOption.Tokenized -> index := Documents.Field.Index.TOKENIZED
        | FieldOption.Type(t) -> value := format t !value
        // The following aren't relevant here
        | FieldOption.Required | FieldOption.Unique
        | FieldOption.MultiValue -> ()

    options |> List.iter setOption
    
    let lfield = new Documents.Field(!name, !value, !store, !index)
    lfield

let convert (doc : Document) = 
    let ldoc = new Documents.Document()
    
    let lFields = doc.Fields |> List.map (buildField doc.Schema)
    
    lFields |> List.iter ldoc.Add    
    ldoc